package es.bwain.xprt.action;

import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Properties;
import java.util.Map.Entry;

public class Initializer {

	private static final long serialVersionUID = 2385739112695455178L;

	public static final String XPRT_ACTION_PACKAGE = "xprt.action.package";
	
	public static final String XPRT_XSLT_PROTOCOL = "xprt.xslt.protocol";
	public static final String XPRT_XSLT_HOST = "xprt.xslt.host";
	public static final String XPRT_XSLT_PORT = "xprt.xslt.port";
	public static final String XPRT_XSLT_USECONTEXTPATH = "xprt.xslt.useContextPath";
	public static final String XPRT_XSLT_FOLDER = "xprt.xslt.folder";
	public static final String XPRT_XSLT_EXTENSION = "xprt.xslt.extension";
	
	public static final String XPRT_DIRECTTOMETHODPARAMETER = "xprt.directToMethodParameter";
	
	private static final String productName = "XPRT"; 
	private static final String version = "0.0.1 beta"; 
	
	private static Hashtable<String, String> initParameters;
	
	/**
	 * @param key Parameter name of the Servlet initialization parameters.
	 * @return Parameter value being requested.
	 */
	public static String getParameter(String key) {
		String response = Initializer.initParameters.get(key);
		if (response != null) {
			response = response.trim();
		}
		return response;
	}
	
	/**
	 * You can change the parameter name by setting the init parameter
	 * "xprt.directToMethodParameter" in the definition of Config File
	 * in xprt.properties. If not set the parameter name is "mthd".
	 * 
	 * @return Parameter name used to send the name of the method to be executed.
	 */
	public static String getDirectToMethodParam() {
		if (initParameters.get(XPRT_DIRECTTOMETHODPARAMETER) != null) {
			return initParameters.get(XPRT_DIRECTTOMETHODPARAMETER);
		} else {
			return "mthd";
		}
	}
	
	/**
	 * @return Product name and version.
	 */
	public static String getVersion() {
		return productName + " " + version;
	}

	public static void initProperties(InputStream configFile) throws IOException {
		
		Properties properties = new Properties();
		properties.load(configFile);
		
		Hashtable<String, String> parameters = new Hashtable<String, String>();
		
		Iterator<Entry<Object, Object>> iter = properties.entrySet().iterator();
		while (iter.hasNext()) {
			Entry<Object, Object> entry = iter.next();
			parameters.put((String)entry.getKey(), (String)entry.getValue());
		}
		
		initParameters = parameters;
	}

}
